package com.cskt.petproject178.service.third;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

import com.aliyun.teaopenapi.models.Config;
import com.cskt.petproject178.config.AliyunSMSAutoConfigProperties;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 阿里云短信发送服务
 *
 * @author 27013
 **/

@Service
public class AliyunSMSService {
    private static  final Logger log= LoggerFactory.getLogger(AliyunSMSService.class);
    @Resource
    private AliyunSMSAutoConfigProperties properties;
    /**
     * 发送短信
     * @param phone 目标手机号
     * @param templateParam 模版参数
     * @return 发送是否成功
     */
    public Boolean sendSms(String phone,String templateParam){
        try {
            //初始化一个配置类
            Config config = new Config();
            config.setAccessKeyId(properties.getAccessKeyId())
                    .setAccessKeySecret(properties.getAccessKeySecret())
                    .setEndpoint(properties.getEndpoint());
            //初始化一个客户端
            Client client = new Client(config);
            //构造请求对象，请填入请求参数值
            SendSmsRequest request=new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(properties.getSignName())
                    .setTemplateCode(properties.getTemplateCode())
                    .setTemplateParam(templateParam);
            // 获取响应对象
            SendSmsResponse response=client.sendSms(request);
            //短信发送结果状态码
            String code = response.getBody().getCode();
            if ("ok".equalsIgnoreCase(code)) {
                log.info("短信发送状态码：{}",code);
                return true;
            }
            return  false;
        } catch (Exception e) {
         log.error("发送短信失败",e);
         return false;
        }
    }
}
